package com.mateng.treasurechest.view.recipe.adapter

import android.content.Intent
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.mateng.treasurechest.R
import com.mateng.treasurechest.model.recipe.bean.MenuSearchBean
import com.mateng.treasurechest.view.recipe.EXTRAS
import com.mateng.treasurechest.view.recipe.activity.RecipeDetailsActivity
import com.mateng.treasurechest.view.recipe.glideOptions

/**
 * Created by mateng on 2018/1/26.
 */
class MenuSearchAdapter(private var arrays: ArrayList<MenuSearchBean.ResultBean.ListBean>?) : RecyclerView.Adapter<MenuSearchAdapter.ViewHolder>() {


    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        holder?.recipeName?.text = arrays?.get(position)?.name
        holder?.coverImageView?.let {
            Glide.with(it).applyDefaultRequestOptions(glideOptions).load(arrays?.get(position)?.thumbnail).into(it)
        }
        holder?.itemView?.setOnClickListener({
            val context = holder.itemView.context
            val intent = Intent(context, RecipeDetailsActivity::class.java)
            intent.putExtra(EXTRAS.KEY_ID, arrays?.get(position)?.menuId)
            intent.putExtra(EXTRAS.KEY_NAME, arrays?.get(position)?.name)

            context?.startActivity(intent)
        })
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item_grid_recipe, parent, false))
    }

    override fun getItemCount(): Int {
        return arrays?.size ?: 0
    }

    fun setNewData(arrays: ArrayList<MenuSearchBean.ResultBean.ListBean>?) {
        arrays?.let { it1 ->
            this.arrays?.addAll(it1)
            this.arrays ?: let {
                this.arrays = ArrayList()
                this.arrays?.addAll(it1)
            }
        }
        notifyDataSetChanged()
    }

    fun cleanData() {
        arrays?.clear()
        notifyDataSetChanged()
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val coverImageView: ImageView = itemView.findViewById(R.id.iv_recipe_cover)
        val recipeName: TextView = itemView.findViewById(R.id.tv_recipe_name)

    }

}